package com.bckj.fastboot.core.extra.license;

import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.Getter;
import lombok.Setter;
import com.github.benmanes.caffeine.cache.Cache;

import java.util.concurrent.TimeUnit;

/**
 * CachedLicenseVerifyServiceImpl
 *
 * @author wfc
 **/
@Getter
@Setter
public class CachedLicenseVerifyServiceImpl implements LicenseVerifyService {


    private final LicenseVerifyService licenseVerifyService;
    private Cache<String, Boolean> licenseCache;
    private final String cacheKey;

    public CachedLicenseVerifyServiceImpl(LicenseVerifyService licenseVerifyService,
                                          String cacheKey, Integer cacheTTL) {
        this.licenseVerifyService = licenseVerifyService;
        this.cacheKey = cacheKey;
        licenseCache = Caffeine.newBuilder()
                .maximumSize(100) // 设置缓存最大容量，防止内存溢出
                .expireAfterWrite(cacheTTL, TimeUnit.MINUTES) // 设置缓存项在写入5分钟后过期
                .build();
    }


    @Override
    public boolean verify() {
        // 1. 尝试从缓存中获取结果
        Boolean cachedResult = licenseCache.getIfPresent(cacheKey);
        if (cachedResult != null) {
            System.out.println("从缓存中获取License状态，结果：" + cachedResult);
            return cachedResult; // 缓存命中，直接返回
        }

        // 2. 缓存无效或不存在，执行实际校验
        boolean actualResult = licenseVerifyService.verify();

        // 3. 将校验结果存入缓存，并设置TTL
        licenseCache.put(cacheKey, actualResult);

        return actualResult;
    }
}
